﻿using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Threading;

namespace SendEmail
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        public List<string> ReadExcel()
        {
            var list = new List<string>();

            var pathList = System.IO.Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "excel"));
            foreach (var item in pathList)
            {
                using (var file = File.OpenRead(item))
                {

                    //根据路径通过已存在的excel来创建HSSFWorkbook，即整个excel文档
                    HSSFWorkbook workbook = new HSSFWorkbook(file);

                    //获取excel的第一个sheet
                    var sheet = workbook.GetSheetAt(0);

                    for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++)
                    {
                        var row = sheet.GetRow(i);

                        for (int j = 0; j < row.LastCellNum; j++)
                        {
                            if (row.LastCellNum >= 3)
                            {
                                var email = row.GetCell(3).StringCellValue;
                                if (!string.IsNullOrEmpty(email))
                                {
                                    list.Add(email);
                                }
                            }
                        }
                    }

                    workbook = null;
                    sheet = null;
                }
            }

            return list;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                var toAddress = ReadExcel();

                Thread thread = new Thread(() =>
                {

                    foreach (var item in toAddress)
                    {
                        try
                        {

                            //确定smtp服务器地址。实例化一个Smtp客户端
                            SmtpClient client = new SmtpClient(txtSmtp.Text);

                            //构造一个发件人地址对象
                            MailAddress from = new MailAddress(txtUserName.Text, txtDisplayName.Text, Encoding.UTF8);

                            //构造一个收件人地址对象
                            MailAddress to = new MailAddress(item, item, Encoding.UTF8);

                            //构造一个Email的Message对象
                            MailMessage message = new MailMessage(from, to);

                            //为 message 添加附件

                            //得到文件名
                            string fileName = txtFiles.Text;
                            //判断文件是否存在
                            if (File.Exists(fileName))
                            {
                                //构造一个附件对象
                                Attachment attach = new Attachment(fileName);
                                //得到文件的信息
                                ContentDisposition disposition = attach.ContentDisposition;
                                disposition.CreationDate = System.IO.File.GetCreationTime(fileName);
                                disposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName);
                                disposition.ReadDate = System.IO.File.GetLastAccessTime(fileName);
                                //向邮件添加附件
                                message.Attachments.Add(attach);
                            }


                            //添加邮件主题和内容
                            message.Subject = txtEmailTitle.Text;
                            message.SubjectEncoding = Encoding.UTF8;
                            message.Body = txtEmailContent.Text;
                            message.BodyEncoding = Encoding.UTF8;

                            //设置邮件的信息
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;
                            message.BodyEncoding = System.Text.Encoding.UTF8;
                            message.IsBodyHtml = false;
                       
                            string username = txtUserName.Text;
                            string passwd = txtPassword.Text;
                            //用户登陆信息
                            client.UseDefaultCredentials = false;
                            NetworkCredential myCredentials = new NetworkCredential(username, passwd);
                            client.Credentials = myCredentials;
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;

                            //发送邮件
                            client.Send(message);

                            listView1.Items.Add(new ListViewItem { Text = DateTime.Now + "发送成功:" + item });
                        }
                        catch (Exception ex)
                        {
                            listView1.Items.Add( new ListViewItem { ForeColor = Color.Red, Text = DateTime.Now + "发送失败:" + item });
                        }

                        Thread.Sleep(1000);
                    }
                });

                thread.IsBackground = true;
                thread.Start();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //定义并初始化一个OpenFileDialog类的对象
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.InitialDirectory = Application.StartupPath;
            openFile.FileName = "";
            openFile.RestoreDirectory = true;
            openFile.Multiselect = false;

            //显示打开文件对话框，并判断是否单击了确定按钮
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                //得到选择的文件名
                txtFiles.Text = openFile.FileName;

            }
        }
    }
}
